package com.tomato.commons.concurrent;


import java.util.Set;
import java.util.concurrent.*;

public class TomatoConcurrent {
    private static final Integer ACPU = Runtime.getRuntime().availableProcessors();

    private static final TomatoThreadFactory factory = new TomatoThreadFactory();

    private static final RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

    private static final ThreadPoolExecutor pool = getThreadPoolExcutor();

    private static final ThreadLocal<Set<CompletableFuture>> threadLocal = new ThreadLocal<>();

    private static ThreadPoolExecutor getThreadPoolExcutor() {
        ThreadPoolExecutor executor =
                new ThreadPoolExecutor(2 * ACPU + 1,
                        2 * ACPU + 1,
                        0,
                        TimeUnit.SECONDS,
                        new LinkedBlockingDeque<>(65535),
                        factory,
                        handler);
        executor.prestartAllCoreThreads();

        return executor;
    }

    public static void execute(Runnable task) {
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(task, pool);
        threadLocal.get().add(completableFuture);
    }
}
